<template>
    <div class="wrapper">
        <div class="left">
            <div class="border">
                <div class="title">校园招聘与社会招聘入职比例</div>
                <div class="leftHeader" style="height: 36vh">
                </div>
            </div>

            <div class="border" style="margin-top: 10px;">
                <div class="title">实习经验对就业薪资的影响</div>
                <div class="leftBottom" style="height: 38vh;"></div>
            </div>

        </div>
        <div class="center">
            <div class="border">
                <div class="title">校友就业情况</div>
                <div class="centertop" style="height: 36vh">
                </div>
            </div>
            <div style="margin-top: 10px;height: 43.5vh;">
                <!-- <div class="title">各行业求职者2024年期望月薪</div> -->
                <!-- <div class="centerBottom" style="height: 38vh;"></div> -->
                <TeachingBuilding />
            </div>
        </div>
        <div class="right">
            <div class="border">
                <div class="title">毕业后就业时间分布</div>
                <div class="righttop" style="height: 36vh;width: 30vw;"></div>
            </div>
            <div class="border" style="margin-top: 10px">
                <div class="title">前十专业就业人数占比</div>
                <div class="rightbottom" style="height: 38vh"></div>
            </div>
        </div>
        <div class="pageTurning pageTurningNext" @click="turnPageNext" style="margin-left: 20px;">
            <svg-icon class="flipArrow" icon-name="arrow" style="width: 23px; height: 23px"></svg-icon>
        </div>
    </div>
</template>
<script setup>
import * as echarts from "echarts";
import { onMounted, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import TeachingBuilding from "@/components/3dTeachingBuilding.vue";
import { getSchoolData } from "@/api/visualizationData";

const route = useRoute();
const router = useRouter();

let funnelChart = null;

//漏斗图
onMounted(async () => {
    const res = await getSchoolData();
    const recruitmentStats = res.data[0].recruitmentStats;

    //漏斗图
    funnelChart = echarts.init(document.querySelector(".leftHeader"));

    // 定义颜色和图例
    const channelColors = {
        "校园招聘": "#8CA9AA",  // 绿色
        "社会招聘": "#F8DAA8"   // 白色
    };

    const option = {
        title: {
            left: "center",
            textStyle: {
                fontSize: 16,
                fontWeight: "bold"
            },
            subtextStyle: {
                fontSize: 12,
                color: "#fff"
            }
        },
        tooltip: {
            trigger: "item",
            formatter: (params) => {
                const stageData = recruitmentStats.find(item => item.stage === params.name);
                let tip = `
          <div style="font-weight:bold;margin-bottom:8px;font-size:14px">
            ${params.name} (总计: ${stageData.total}人)
          </div>
          <table style="width:100%;border-collapse:collapse;">
            <tr style="background:#f5f5f5">
              <th style="padding:4px 8px;text-align:left;">渠道</th>
              <th style="padding:4px 8px;text-align:right;">人数</th>
              <th style="padding:4px 8px;text-align:right;">占比</th>
            </tr>`;
                stageData.composition.forEach(item => {
                    const percent = ((item.value / stageData.total) * 100).toFixed(1);
                    tip += `
            <tr>
              <td style="padding:4px 8px;">
                <span style="display:inline-block;width:12px;height:12px;background:${channelColors[item.name]};margin-right:6px;vertical-align:middle;"></span>
                ${item.name}
              </td>
              <td style="padding:4px 8px;text-align:right;">${item.value}人</td>
              <td style="padding:4px 8px;text-align:right;">${percent}%</td>
            </tr>`;
                });

                tip += `</table>`;
                return tip;
            },
            backgroundColor: "#fff",
            borderColor: "#ddd",
            borderWidth: 1,
            padding: [10, 12],
            textStyle: {
                color: "#333"
            }
        },
        legend: {
            data: Object.keys(channelColors).map(name => ({
                name: name,
                icon: "rect",
                itemStyle: { color: channelColors[name] }
            })),
            bottom: 10,
            left: "center",
            itemWidth: 16,
            itemHeight: 12,
            textStyle: {
                fontSize: 12,
                padding: [0, 5, 0, 0]
            },
            formatter: function (name) {
                return `{color|■} ${name}`;
            },
            tooltip: {
                show: true,
                formatter: function (item) {
                    return `${item.name}渠道数据`;
                }
            }
        },
        series: [{
            name: "招聘流程",
            type: "funnel",
            left: "15%",
            top: "15%",
            bottom: "20%",
            width: "70%",
            gap: 8,
            label: {
                show: true,
                position: "inside",
                formatter: "{b}\n总人数: {c}",
                fontSize: 12,
                color: "#fff",
                fontWeight: "bold",
                lineHeight: 18
            },
            labelLine: {
                show: false
            },
            itemStyle: {
                borderColor: "#fff",
                borderWidth: 2,
                borderRadius: 6
            },
            data: recruitmentStats.map(stage => ({
                name: stage.stage,
                value: stage.total,
                itemStyle: {
                    color: {
                        type: "linear",
                        x: 0,
                        y: 0,
                        x2: 1,
                        y2: 0,
                        colorStops: stage.composition.reduce((stops, item, index, arr) => {
                            const offset = index === 0 ? 0 :
                                arr.slice(0, index).reduce((sum, x) => sum + x.value, 0) / stage.total;
                            stops.push({ offset, color: channelColors[item.name] });
                            if (index === arr.length - 1) {
                                stops.push({ offset: 1, color: channelColors[item.name] });
                            }
                            return stops;
                        }, [])
                    }
                }
            }))
        }],
        graphic: [{
            type: "text",
            left: "center",
            top: "88%"
        }, {
            type: "text",
            left: "center",
            top: "92%",
            style: {
                text: "🟢 绿色代表校园招聘 | 🟡 橙色代表社会招聘",
                fill: "#fff",
                fontSize: 12
            }
        }]
    };

    funnelChart.setOption(option);

    const handleResize = () => funnelChart?.resize();
    window.addEventListener("resize", handleResize);
    onBeforeUnmount(() => {
        window.removeEventListener("resize", handleResize);
        funnelChart?.dispose();
    });
});

//校友就业情况（平行坐标图）
onMounted(async () => {
    const res = await getSchoolData();
    const alumniEmployment = res.data[0].alumniEmployment;

    let parallelChart = null;
    parallelChart = echarts.init(document.querySelector(".centertop"));

    const graduationYears = alumniEmployment.map(item => `${item.gradYear}届`);
    const dimensions = [
        '毕业年份',
        '平均薪资(元)',
        '就业率(%)',
        '深造率(%)',
        '一线城市就业比例(%)',
        '专业对口率(%)'
    ];

    const data = alumniEmployment.map(item => [
        `${item.gradYear}届`,
        parseFloat(item.avgSalary),
        parseFloat(item.employmentRate.replace('%', '')),
        parseFloat(item.furtherStudyRate.replace('%', '')),
        parseFloat(item.firstTierRate.replace('%', '')),
        parseFloat(item.majorRelevance.replace('%', ''))
    ]);

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                const yearData = data[params.dataIndex];
                let result = `<div style="font-weight:bold;margin-bottom:8px">${graduationYears[params.dataIndex]}校友数据</div>`;
                dimensions.forEach((dim, index) => {
                    if (index > 0) { // 跳过第一个维度（年份）
                        result += `<div style="margin:3px 0">
              <span style="display:inline-block;width:150px">${dim}</span>: 
              <span style="font-weight:bold">${yearData[index]}</span>
            </div>`;
                    }
                });
                return result;
            }
        },
        legend: {
            data: graduationYears,
            bottom: 10,
            textStyle: {
                fontSize: 12
            }
        },
        parallelAxis: [
            { dim: 0, name: dimensions[0], type: 'category', data: graduationYears },
            { dim: 1, name: dimensions[1], max: 15000, axisLabel: { formatter: '{value}元' } },
            { dim: 2, name: dimensions[2], max: 100, axisLabel: { formatter: '{value}%' } },
            { dim: 3, name: dimensions[3], max: 100, axisLabel: { formatter: '{value}%' } },
            { dim: 4, name: dimensions[4], max: 100, axisLabel: { formatter: '{value}%' } },
            { dim: 5, name: dimensions[5], max: 100, axisLabel: { formatter: '{value}%' } }
        ],
        parallel: {
            left: '5%',
            right: '15%',
            bottom: '15%',
            top: '15%',
            parallelAxisDefault: {
                type: 'value',
                nameTextStyle: {
                    fontSize: 12,
                    color: '#fff'
                },
                axisLine: {
                    lineStyle: {
                        color: '#aaa'
                    }
                },
                axisTick: {
                    lineStyle: {
                        color: '#aaa'
                    }
                },
                splitLine: {
                    show: false
                },
                axisLabel: {
                    color: '#fff'
                }
            }
        },
        series: {
            name: '校友就业数据',
            type: 'parallel',
            lineStyle: {
                width: 2,
                opacity: 0.8
            },
            data: data,
            emphasis: {
                lineStyle: {
                    width: 4,
                    shadowColor: 'rgba(0,0,0,0.3)',
                    shadowBlur: 10,
                    shadowOffsetY: 5
                }
            }
        },
        color: [
            '#F8DAA8', '#91CC75', '#FAC858', '#EE6666',
            '#73C0DE', '#3BA272', '#FC8452', '#9A60B4'
        ]
    };

    parallelChart.setOption(option);

    const handleResize = () => parallelChart?.resize();
    window.addEventListener('resize', handleResize);
    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize);
        parallelChart?.dispose();
    });
});

//散点图（实习经验对就业薪资的影响）
onMounted(async () => {
    const res = await getSchoolData();
    const internshipSalary = res.data[0].internshipSalary;

    let scatterChart = null;
    scatterChart = echarts.init(document.querySelector(".leftBottom"));
    const data = internshipSalary.map(item => [item.experience, item.avgSalary]);

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                const experience = params.value[0];
                const avgSalary = params.value[1];
                return `实习经验：${experience}<br>平均薪资：${avgSalary}元`;
            }
        },
        grid: {
            left: '5%', // 增加左侧边距
            right: '20%', // 增加右侧边距
            top: '20%', // 增加上边边距
            bottom: '20%', // 增加下边边距
            containLabel: true // 确保标签不超出边界
        },
        xAxis: {
            name: '实习经验',
            type: 'category',
            data: internshipSalary.map(item => item.experience),

            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            },
            axisLabel: {
                textStyle: {
                    color: '#FFFFFF' // 设置 X 轴标签的字体颜色
                },
                interval: 0,
            },
            nameTextStyle: {
                color: '#FFFFFF' // 设置 X 轴名称的字体颜色
            }
        },
        yAxis: {
            name: '平均薪资（元）',
            type: 'value',
            scale: true,
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            },
            axisLabel: {
                textStyle: {
                    color: '#FFFFFF' // 设置 Y 轴标签的字体颜色
                }
            },
            nameTextStyle: {
                color: '#FFFFFF' // 设置 Y 轴名称的字体颜色
            }
        },
        series: [
            {
                name: '实习经验与平均薪资',
                type: 'scatter',
                symbolSize: 10,
                data: data,
                markLine: {
                    lineStyle: {
                        type: 'dashed'
                    },
                    data: [
                        { type: 'average', name: '平均值' }
                    ]
                },
                itemStyle: {
                    normal: {
                        color: '#D69955', // 点的颜色
                        borderColor: '#5470C6', // 点的边框颜色
                        borderWidth: 1
                    }
                },
                emphasis: {
                    itemStyle: {
                        borderColor: '#FFFFFF', // 高亮时的边框颜色
                        borderWidth: 2
                    }
                }
            }
        ]
    };

    scatterChart.setOption(option);

    const handleResize = () => scatterChart?.resize();
    window.addEventListener('resize', handleResize);
    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize);
        scatterChart?.dispose();
    });
});

//饼图
onMounted(async () => {
    const res = await getSchoolData();
    const majorEmploymentStats = res.data[0].majorEmploymentStats;

    let pieChart = null;
    pieChart = echarts.init(document.querySelector(".rightbottom"));

    const majors = majorEmploymentStats.map(item => item.major);
    const employmentCounts = majorEmploymentStats.map(item => item.count);

    const totalEmployment = employmentCounts.reduce((sum, count) => sum + count, 0);

    const data = majorEmploymentStats.map(item => ({
        name: item.major,
        value: item.count
    }));

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                const percent = ((params.value / totalEmployment) * 100).toFixed(2);
                return `${params.name}<br>就业人数：${params.value}人<br>占比：${percent}%`;
            }
        },
        series: [
            {
                name: '就业人数',
                type: 'pie',
                radius: '50%',
                data: data,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                label: {
                    formatter: '{b}'
                },
                labelLine: {
                    show: true
                },
                color: ['#D69955', '#F8DAA8', '#E4DCCF', '#8CA9AA', '#DCDCDC'] // 自定义颜色数组
            }
        ]
    };

    pieChart.setOption(option);

    const handleResize = () => pieChart?.resize();
    window.addEventListener('resize', handleResize);
    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize);
        pieChart?.dispose();
    });
});

//时间序列图（折线图）
onMounted(async () => {
    const res = await getSchoolData();
    const jobTimeDist = res.data[0].jobTimeDist;

    let timeSeriesChart = null;
    timeSeriesChart = echarts.init(document.querySelector(".righttop"));

    const monthsAfterGraduation = jobTimeDist.map(item => item.timePeriod);
    const employmentCounts = jobTimeDist.map(item => parseFloat(item.ratio2024.replace('%', '')));

    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                const timePeriod = params[0].name;
                const employmentRate = params[0].data;
                return `${timePeriod}<br>就业比例：${employmentRate}%`;
            }
        },
        grid: {
            left: '5%', // 增加左侧边距
            right: '15%', // 增加右侧边距
            top: '15%', // 增加上边边距
            bottom: '3%', // 增加下边边距
            containLabel: true // 确保标签不超出边界
        },
        xAxis: {
            name: '时间区间',
            type: 'category',
            data: monthsAfterGraduation,
            boundaryGap: false,
            axisLabel: {
                textStyle: {
                    color: '#fff' // X 轴标签字体颜色
                },
                interval: 0,
                rotate: -30, // 将标签旋转45度，避免重叠
                margin: 10, // 增加标签与轴线的间距
            },
            nameTextStyle: {
                color: '#fff' // X 轴名称字体颜色
            }
        },
        yAxis: {
            name: '就业比例(%)',
            type: 'value',
            axisLabel: {
                textStyle: {
                    color: '#fff' // Y 轴标签字体颜色
                }
            },
            nameTextStyle: {
                color: '#fff' // Y 轴名称字体颜色
            }
        },
        series: [
            {
                name: '就业比例',
                type: 'line',
                data: employmentCounts,
                symbol: 'circle', // 数据点的形状
                symbolSize: 6, // 数据点的大小
                lineStyle: {
                    width: 2,
                    color: '#F8DAA8' // 线条颜色
                },
                itemStyle: {
                    color: '#D69955' // 数据点颜色
                },
                emphasis: {
                    itemStyle: {
                        borderColor: '#FFFFFF', // 高亮时的边框颜色
                        borderWidth: 2
                    }
                }
            }
        ]
    };

    timeSeriesChart.setOption(option);

    const handleResize = () => timeSeriesChart?.resize();
    window.addEventListener('resize', handleResize);
    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize);
        timeSeriesChart?.dispose();
    });
});

//跳转后一页
const turnPageNext = () => {
    router.push({
        path: "/home",
        // query: { id: noticeData.value.nextId },
    });
};

</script>

<style lang="scss" scoped>
// 标题公共样式
.title {
    width: 100%;
    border-bottom-left-radius: 50px;
    border-top-left-radius: 50px;
    color: #000;
    padding: 5px 0px 5px 10px;
    margin: 5px;
    display: inline-block;
    background: linear-gradient(to right,
            #F0EBE3,
            rgba(240, 235, 227, 0.8),
            rgba(240, 235, 227, 0.6),
            rgba(240, 235, 227, 0.4),
            rgba(240, 235, 227, 0.2),
            rgba(240, 235, 227, 0));
}

.border {
    background: linear-gradient(to left, #DCDCDC, #DCDCDC) left top no-repeat,
        linear-gradient(to bottom, #DCDCDC, #DCDCDC) left top no-repeat,
        linear-gradient(to left, #DCDCDC, #DCDCDC) right top no-repeat,
        linear-gradient(to bottom, #DCDCDC, #DCDCDC) right top no-repeat,
        linear-gradient(to left, #DCDCDC, #DCDCDC) left bottom no-repeat,
        linear-gradient(to bottom, #DCDCDC, #DCDCDC) left bottom no-repeat,
        linear-gradient(to left, #DCDCDC, #DCDCDC) right bottom no-repeat,
        linear-gradient(to left, #DCDCDC, #DCDCDC) right bottom no-repeat;
    background-size: 2px 20px, 20px 2px, 2px 20px, 20px 2px, 2px 20px, 20px 2px,
        2px 20px, 20px 2px;
    border: 1px solid #576F72;
    position: relative;
}

.wrapper {
    display: flex;
    overflow: hidden;
    min-height: 90vh;

}

.left {
    width: 33%;
}

.center {
    width: 34%;
    height: 87vh;
    margin-left: 10px;
    margin-right: 10px;
}

.right {
    width: 33%;
}

.pageTurning {
    margin-top: 36vh;
    width: 50px;
    height: 45px;
    background-color: #fff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    /* 添加过渡效果 */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    /* 初始阴影效果 */
}

.pageTurningNext:hover {
    transform: translateY(-5px) translateX(5px);
    /* 鼠标移动时向上浮动 */
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    /* 鼠标移动时增强阴影效果 */
}

.pageTurningPre:hover {
    transform: translateY(-5px) translateX(-5px);
    /* 鼠标移动时向上浮动 */
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    /* 鼠标移动时增强阴影效果 */
}

.flipArrow {
    transform: rotate(180deg);
    /* 立即旋转 180 度，不使用过渡动画 */
}

:deep(img) {
    width: 80%;
}
</style>